import {
	createStore
} from 'vuex'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth.js';
import {
	loginByPhone,
	loginByWeChat,
	getUserInfo
} from "@/api";

// 处理登录成功逻辑
function handleLoginSuccess(commit, token) {
	commit("SET_TOKEN", token);
	commit("SET_IS_LOGIN", true);
	setToken(token);
	uni.showToast({
		title: "登录成功"
	})
	setTimeout(() => {
		uni.navigateBack({
			delta: 1,
			fail: () => {
				uni.reLaunch({
					url: "/pages/home/index"
				})
			}
		})
	}, 1000)
}

const store = createStore({
	state: {
		// 用户认证token
		token: getToken(),
		// 用户信息
		userInfo: {},
		// 是否登录
		isLogin: false
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo
		},
		SET_IS_LOGIN: (state, isLogin) => {
			state.isLogin = isLogin
		}
	},
	actions: {
		// 手机号登录
		LoginByPhone({
			commit
		}, data) {
			return new Promise(async (resolve, reject) => {
				const res = await loginByPhone(data);
				handleLoginSuccess(commit, res.data.token);
				resolve(res);
			})
		},
		// 微信授权登录
		LoginByWeChat({
			commit
		}, data) {
			return new Promise(async (resolve, reject) => {
				const res = await loginByWeChat(data);
				handleLoginSuccess(commit, res.data.token);
				resolve(res);
			})
		},
		// 获取用户信息
		GetUserInfo({
			commit
		}) {
			return new Promise(async (resolve, reject) => {
				const res = await getUserInfo();
				commit("SET_USERINFO", res.data);
				if (JSON.stringify(res.data) === "{}") {
					commit("SET_IS_LOGIN", false);
				} else {
					commit("SET_IS_LOGIN", true);
				}
				resolve(res);
			})
		},
		// 退出登录
		Logout({
			commit
		}) {
			removeToken();
			commit("SET_TOKEN", null);
			commit("SET_IS_LOGIN", false);
			commit("SET_USERINFO", {});
		}
	}
})

export default store;